package de.fh.ka.as.car;

import android.app.Activity;
import android.content.SharedPreferences;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.text.format.Formatter;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class CarPreferences extends Activity implements OnClickListener {
	private TextView localIPAddress, serverIPAdress;
	private Button save, refresh;

	public static final String KEY_SERVER_IP_ADDRESS = "serveridAdress";
	private static String SERVER_IP_ADDRESS = "-";
	public static String S = "-";

	public SharedPreferences setting;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.preferences);
		localIPAddress = (TextView) findViewById(R.id.local_ip_adress);
		serverIPAdress = (TextView) findViewById(R.id.server_ip_adress);
		save = (Button) findViewById(R.id.save);
		save.setOnClickListener(this);
		refresh = (Button) findViewById(R.id.refresh);
		refresh.setOnClickListener(this);
		readLoaclIP();
		setting = getSharedPreferences(AppStarter.PREFS_NAME, 0);
		refreshServerIP();
	}

	public void refreshServerIP() {
		String ip = setting.getString(KEY_SERVER_IP_ADDRESS, "-");
		serverIPAdress.setText(ip);
		SERVER_IP_ADDRESS = ip;
	}

	public void saveServerIP() {
		SharedPreferences.Editor editor = setting.edit();
		String newIP = serverIPAdress.getText().toString();
		editor.putString(KEY_SERVER_IP_ADDRESS, newIP);
		SERVER_IP_ADDRESS = newIP;
		Log.i("IOIONetwork", "saved ip: " + newIP);
		editor.commit();
	}

	public void readLoaclIP() {
		WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
		WifiInfo wifiInfo = wifiManager.getConnectionInfo();
		localIPAddress.setText(Formatter.formatIpAddress(wifiInfo.getIpAddress()));
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.save:
				saveServerIP();
				break;
			case R.id.refresh:
				readLoaclIP();
				refreshServerIP();
				break;
		}

	}

	public static void setIP_ADDRESS(String iP_ADDRESS) {
		SERVER_IP_ADDRESS = iP_ADDRESS;
	}

	public static String getIP_ADDRESS() {
		return SERVER_IP_ADDRESS;
	}

}
